package com.carl;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.MaxAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;
import java.util.Map;

public class Context_Query {
    public static void main(String[] args) throws IOException {
        //创建es客户端
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.73.130", 9200, "http")));


        //创建搜索对象
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("user");

//        //构建查询请求体 1.全量查询
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//        searchRequest.source(searchSourceBuilder);
//        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
//
//          //2.查询条件为关键字
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        searchSourceBuilder.query(QueryBuilders.termQuery("age",30));
//        searchRequest.source(searchSourceBuilder);
//        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

//             //3.分页查询
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//        //分页查询
//       // 当前页其实索引(第一条数据的顺序号)，from   比如查询第二页数据 （2-1）* 2 = 2 从第二条开始查
//        searchSourceBuilder.from(2);
//        // 每页显示多少条 size
//        searchSourceBuilder.size(2);
//        searchRequest.source(searchSourceBuilder);
//        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

//           //4.数据排序
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//        searchSourceBuilder.sort("age", SortOrder.DESC);
//        searchRequest.source(searchSourceBuilder);
//        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
//          //5.过滤字段
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//        //查询字段过滤
//        String[] excludes = {};
//        String[] includes = {"name", "age"};
//        searchSourceBuilder.fetchSource(includes,excludes);
//        searchRequest.source(searchSourceBuilder);
//        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

//         //6.Bool 查询
//            // 构建查询的请求体
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//            // 必须包含
//        boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30"));
//           // 一定不含
//        boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "zhangsan"));
//           // 可能包含
//        boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));
//        sourceBuilder.query(boolQueryBuilder);
//        searchRequest.source(sourceBuilder);
//        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

//           //7.范围查询
//          SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//          RangeQueryBuilder queryBuilder = QueryBuilders.rangeQuery("age");
//          //年龄大于30 小于40
//          queryBuilder.gte("30");
//          queryBuilder.lte("40");
//          sourceBuilder.query(queryBuilder);
//          searchRequest.source(sourceBuilder);
//          SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

//          //8.模糊查询
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        FuzzyQueryBuilder fuzziness = QueryBuilders
//                .fuzzyQuery("name", "wangwu").fuzziness(Fuzziness.ONE); //偏移量是1
//        sourceBuilder.query(fuzziness);
//        searchRequest.source(sourceBuilder);
//        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

//          //9.高亮查询
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        //构建查询方式:高亮查询
//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zhangsan");
//        //构建高亮字段
//        HighlightBuilder highlightBuilder = new HighlightBuilder();
//        highlightBuilder.preTags("<font color='red'>");//设置标签前缀
//        highlightBuilder.postTags("</font>");//设置标签后缀
//        highlightBuilder.field("name");//设置高亮字段
//        //设置查询方式 和高亮构建对象
//        sourceBuilder.query(termQueryBuilder).highlighter(highlightBuilder);
//        searchRequest.source(sourceBuilder);
//        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
//
//        // 查询匹配
//        SearchHits hits = response.getHits();
//        System.out.println("took:" + response.getTook());
//        System.out.println("timeout:" + response.isTimedOut());
//        System.out.println("total:" + hits.getTotalHits());
//        System.out.println("MaxScore:" + hits.getMaxScore());
//        System.out.println("hits========>>");
//        for (SearchHit hit : hits) {
//            //输出每条查询的结果信息
//            System.out.println(hit.getSourceAsString());
//            //打印高亮结果
//            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
//            System.out.println(highlightFields);
//        }
//        System.out.println("<<========");

         //10.聚合查询最大年龄
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        MaxAggregationBuilder maxAggregationBuilder = AggregationBuilders.max("maxAge").field("age");
        sourceBuilder.aggregation(maxAggregationBuilder);
        searchRequest.source(sourceBuilder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(response);

//         //11.分组统计
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("age_Group").field("age");
//        sourceBuilder.aggregation(termsAggregationBuilder);
//        searchRequest.source(sourceBuilder);
//        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
//        System.out.println(response);



        client.close();
    }
}
